package com.zemb.flxwear.UI.Fragment;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.neurosky.AlgoSdk.NskAlgoSdk;
import com.zemb.flxwear.Bean.ReportItem;
import com.zemb.flxwear.DB.DataBaseHelper;
import com.zemb.flxwear.R;
import com.zemb.flxwear.UI.CustomView.EcgWindow;
import com.zemb.flxwear.Utils.DeviceUtils;
import com.zemb.flxwear.Utils.LogUtils;
import com.zemb.flxwear.Utils.VoicePlayUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class ECGFragment extends BaseFragment implements View.OnClickListener {

    private EcgWindow ecgWindow;
    private Button measureButton;
    private TextView deviceName, measureData;
    private View v_top_panel;
    private NskAlgoSdk nskAlgoSdk;
    private List<Integer> ecgData = new ArrayList<>();
    private int index = 0;
    private List<Integer> result = new ArrayList<>();
    private DataBaseHelper.ECG ecg;


    @Override
    int getLoadingPageId() {
        return R.id.loading_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_ecg;
    }

    @Override
    void onNotifyCallBack(byte[] data) {
        LogUtils.PrintLog("接受到数据" + Arrays.toString(data));
        switch (data[2]) {
            case 0x06:
                ecgWindow.stopDraw();
                break;
            case 16:
                ecgWindow.startDraw();
                onMeasureStart();
                for (int i = 3; i < data.length - 1; i += 2) {
                    byte high = data[i];
                    byte low = data[i + 1];
                    short shortValue = (short) ((high & 0xFF) * 256 + (low & 0xFF));
                    int intValue = (int) shortValue;
                    if (intValue >= 32768) {
                        intValue -= 65536;
                    }
                    result.add(intValue);
                }
                measureButton.setText(String.format("%.1f%%", result.size() / 15000.0 * 100));
                break;
        }
        if (result.size() >= 15000) {
            ecg.EGCData = result.toString();
            ecg.date = getCurrentTime();
            onMeasureComplete();
        }
    }

    @Override
    protected void initView(View root) {
        ecgWindow = root.findViewById(R.id.ecg_window);
        measureButton = root.findViewById(R.id.btn_measure);
        measureButton.setOnClickListener(this);
        deviceName = root.findViewById(R.id.tv_device_name);
        if (activity.getCurrentDevice() != null) {
            deviceName.setText(activity.getCurrentDevice().getName());
        } else {
            deviceName.setText(getString(R.string.click_connect_device));
        }
        measureData = root.findViewById(R.id.tv_ecg_data);
        v_top_panel = root.findViewById(R.id.v_top_panel);
        v_top_panel.setOnClickListener(this);
        measureData.setText(getResourceString(R.string.disconnect));
    }

    @Override
    protected void initData() {
        LogUtils.PrintLog("初始化数据");
        //获取数据

        //判断设备是否使自己需要的设备 如果是的话就显示设备名称 如果不是的就断开设备连接
        ecg = new DataBaseHelper.ECG();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_measure:
                ecgWindow.startDraw();
                break;
            case R.id.v_top_panel:
                activity.switchFragment(DeviceUtils.UIType.CONNECT);
                break;
            default:
                return;
        }
    }

    @Override
    public void onStartConnectDevice() {
        VoicePlayUtils.getInstance().PlayConnectStart(activity.getMeasureTag());
        showLoading(getResourceString(R.string.connecting));
    }

    @Override
    public void onDeviceConnect(BleDevice bleDevice) {
        VoicePlayUtils.getInstance().PlayConnectSuccess(activity.getMeasureTag());
        deviceName.setText(bleDevice.getName());
        measureData.setText(getResourceString(R.string.wait_measure));
        measureButton.setText(getResourceString(R.string.wait_measure));
        openNotify();
    }

    @Override
    public void onDeviceDisConnected(BleDevice bleDevice) {
        VoicePlayUtils.getInstance().PlayDisconnect(activity.getMeasureTag());
        if(!isSuccessful&&isMeasure){
            onMeasureFailed();
        }

        deviceName.setText(getResourceString(R.string.click_connect_device));
        measureData.setText(getResourceString(R.string.disconnect));
        measureButton.setText(getResourceString(R.string.disconnect));
        isMeasure = false;
        hideLoading();
    }

    @Override
    public void onDeviceConnectFail(BleDevice bleDevice, BleException exception) {
        hideLoading();
        VoicePlayUtils.getInstance().PlayConnectFailed(activity.getMeasureTag());
    }

    @Override
    public void onMeasureComplete() {
        showLoading(getResourceString(R.string.uploading));
        VoicePlayUtils.getInstance().PlayMeasureSuccess(activity.getMeasureTag());
        BleManager.getInstance().stopNotify(activity.getCurrentDevice(), service_uuid, characteristic_uuid);
        ecgWindow.stopDraw();
        measureData.setText(getResourceString(R.string.measure_complete));
        measureButton.setText(getResourceString(R.string.measure_complete));
        ecg.date = getCurrentTime();
        DataBaseHelper.getInstance(activity).addECG(ecg);
        result.clear();
        if (isAuto) {
            if (isAuto) {
                ReportItem item = new ReportItem();
                item.type = DeviceUtils.Category.ECG;
                item.result = "Please check on the webpage";
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                item.time = sdf.format(new Date(ecg.date));
                activity.finishTask(item);
            }
        }
        hideLoading();
        isMeasure = false;
        isSuccessful = true;
    }

    @Override
    public void onMeasureStart() {
        if (isMeasure||isSuccessful) {
            return;
        }
        VoicePlayUtils.getInstance().PlayMeasureStart(activity.getMeasureTag());
        showLoading(getResourceString(R.string.wait_measure));
        isMeasure = true;
    }

    @Override
    public String getCharacteristicHead() {
        return "f000bb01";
    }

    @Override
    void closeNotify() {
        BleManager.getInstance().stopNotify(activity.getCurrentDevice(), service_uuid, characteristic_uuid);
    }
}
